package org.jsola.hr.service.impl;

import org.jsola.core.Page;
import org.jsola.exception.ParamException;
import org.jsola.hr.common.ExampleKit;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.dao.IChannelGroupUserDAO;
import org.jsola.hr.dto.ChannelGroupJurisdictionAddDTO;
import org.jsola.hr.dto.ChannelGroupUserAddDTO;
import org.jsola.hr.dto.ChannelGroupUserUpdateDTO;
import org.jsola.hr.entity.ChannelGroupJurisdictionDO;
import org.jsola.hr.entity.ChannelGroupUserDO;
import org.jsola.hr.provider.IPermissionProviderService;
import org.jsola.hr.provider.IUserProviderService;
import org.jsola.hr.query.ChannelGroupJurisdictionQuery;
import org.jsola.hr.query.ChannelGroupUserQuery;
import org.jsola.hr.service.IChannelGroupJurisdictionService;
import org.jsola.hr.service.IChannelGroupService;
import org.jsola.hr.service.IChannelGroupUserService;
import org.jsola.hr.vo.ChannelGroupJurisdictionListVO;
import org.jsola.hr.vo.ChannelGroupUserListVO;
import org.jsola.hr.vo.ChannelGroupUserVO;
import org.jsola.hr.vo.ChannelGroupVO;
import org.jsola.permission.constant.PermissionConstants;
import org.jsola.permission.entity.RoleDO;
import org.jsola.user.core.TokenUser;
import org.jsola.user.entity.UserDO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

import static org.jsola.hr.constant.HrPermissionConstants.HR_DEFAULT_SUBJECT_ID;
import static org.jsola.hr.constant.HrPermissionConstants.SYSTEM_SUBJECT_TYPE;

/**
 * 渠道分组用户中间表
 *
 * @author zhr
 */
@Service("hrChannelGroupUserServiceImpl")
public class ChannelGroupUserServiceImpl implements IChannelGroupUserService {

    @Autowired
    private IChannelGroupUserDAO channelGroupUserDAO;

    @Autowired
    private IChannelGroupJurisdictionService channelGroupJurisdictionService;

    @Autowired
    private IChannelGroupService channelGroupService;

    @Autowired
    private IUserProviderService userProviderService;

    @Autowired
    private IPermissionProviderService permissionProviderService;

    @Override
    public Integer deleteGroupManager(ChannelGroupUserQuery channelGroupUserQuery, TokenUser tokenUser) {
        if (channelGroupUserQuery.getJurisdiction() == 1 || channelGroupUserQuery.getJurisdiction() == 2) {
            channelGroupJurisdictionService.deleteByIds(tokenUser, channelGroupUserQuery.getManagerId());
        } else {
            deleteByIds(tokenUser, channelGroupUserQuery.getManagerId());
        }
        return 1;
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public Integer batchSave(ChannelGroupUserAddDTO channelGroupUserAddDTO, TokenUser tokenUser) {
        if ("DEFAULT".equals(channelGroupUserAddDTO.getChannelGroupId())) {
            for (String userId : channelGroupUserAddDTO.getUserIdList()) {
                ChannelGroupJurisdictionAddDTO channelGroupJurisdictionAddDTO = new ChannelGroupJurisdictionAddDTO();
                channelGroupJurisdictionAddDTO.setJurisdiction(1);
                channelGroupJurisdictionAddDTO.setUserId(userId);
                channelGroupJurisdictionService.save(channelGroupJurisdictionAddDTO, tokenUser);
            }
        } else {
            ChannelGroupVO channelGroupVO = channelGroupService.selectById(channelGroupUserAddDTO.getChannelGroupId(), tokenUser.getSiteId());
            ParamException.notNull(channelGroupVO, "未找到指定渠道分组");
            if (channelGroupVO.getLevel() == 1) {
                for (String userId : channelGroupUserAddDTO.getUserIdList()) {
                    ChannelGroupJurisdictionAddDTO channelGroupJurisdictionAddDTO = new ChannelGroupJurisdictionAddDTO();
                    channelGroupJurisdictionAddDTO.setJurisdiction(2);
                    channelGroupJurisdictionAddDTO.setUserId(userId);
                    channelGroupJurisdictionService.save(channelGroupJurisdictionAddDTO, tokenUser);
                }
            } else if (channelGroupVO.getLevel() == 2) {
                for (String userId : channelGroupUserAddDTO.getUserIdList()) {
                    ChannelGroupUserAddDTO channelGroupUserAddDTO1 = new ChannelGroupUserAddDTO();
                    channelGroupUserAddDTO1.setChannelGroupId(channelGroupUserAddDTO.getChannelGroupId());
                    channelGroupUserAddDTO1.setUserId(userId);
                    ChannelGroupUserQuery cgq = channelGroupUserAddDTO1.to(ChannelGroupUserQuery.class);
                    cgq.setGroupId(channelGroupUserAddDTO.getChannelGroupId());
                    List<ChannelGroupUserListVO> select = select(cgq, tokenUser.getSiteId());
                    if (CollectionUtils.isEmpty(select)) {
                        save(channelGroupUserAddDTO1, tokenUser);
                    }
                }
            }
        }
        return 0;
    }

    @Override
    public List<ChannelGroupUserDO> selectGroupByUserId(String userId, TokenUser tokenUser) {
        Example example = new Example(ChannelGroupUserDO.class);
        example.and()
                .andEqualTo("valid", true)
                .andEqualTo("siteId", tokenUser.getSiteId())
                .andEqualTo("userId", userId);
        return channelGroupUserDAO.selectByExample(example);
    }

    @Override
    public List<ChannelGroupUserListVO> getUserByGroupId(ChannelGroupUserQuery channelGroupUserQuery, TokenUser tokenUser) {
        List<ChannelGroupUserListVO> channelGroupUserListVOList = new ArrayList<>();
        String userId = null;
        if (channelGroupUserQuery.getJurisdiction() == 2) {
            //获取首位超级管理员的user
            userId = permissionProviderService.findMemberIdBySubject(PermissionConstants.ROLE_MEMBER_TYPE_USER,
                    SYSTEM_SUBJECT_TYPE, HR_DEFAULT_SUBJECT_ID, tokenUser.getSiteId());
            UserDO userDO = userProviderService.selectUserById(userId);
            ChannelGroupUserListVO channelGroupUserListVO = new ChannelGroupUserListVO();
            channelGroupUserListVO.setPhone(userDO.getPhone());
            channelGroupUserListVO.setUserName(userDO.getName());
            channelGroupUserListVO.setUserId(userDO.getId());
            channelGroupUserListVOList.add(channelGroupUserListVO);
        }
        //默认分组
        if (channelGroupUserQuery.getJurisdiction() == 1 || channelGroupUserQuery.getJurisdiction() == 2) {
            List<ChannelGroupJurisdictionDO> allManagerByJurisdiction = channelGroupJurisdictionService.getAllManagerByJurisdiction(channelGroupUserQuery.getJurisdiction(), tokenUser);
            for (ChannelGroupJurisdictionDO channelGroupJurisdictionDO : allManagerByJurisdiction) {
                ChannelGroupUserListVO channelGroupUserListVO = channelGroupJurisdictionDO.to(ChannelGroupUserListVO.class);
                UserDO userDO = userProviderService.selectUserById(channelGroupJurisdictionDO.getUserId());
                if (userDO != null && userDO.getId() != null) {
                    channelGroupUserListVO.setUserName(userDO.getName());
                    channelGroupUserListVO.setPhone(userDO.getPhone());
                }
                channelGroupUserListVOList.add(channelGroupUserListVO);
            }
        } else {
            channelGroupUserListVOList = channelGroupUserDAO.getUserByGroupId(channelGroupUserQuery.getGroupId(), tokenUser.getSiteId());
        }
        if (CollectionUtils.isEmpty(channelGroupUserListVOList)) {
            return new ArrayList<>();
        }
        Iterator<ChannelGroupUserListVO> iterator = channelGroupUserListVOList.iterator();
        while (iterator.hasNext()) {
            ChannelGroupUserListVO next = iterator.next();
            if(!StringUtils.isEmpty(next.getUserId()) && userId != null && !userId.equals(next.getUserId())){
                List<RoleDO> roleListByUserId = permissionProviderService.findRoleListByUserId(next.getUserId(), HrConstants.HR_SUBJECT_TYPE, 0 + "", tokenUser.getSiteId());
                if (CollectionUtils.isEmpty(roleListByUserId)) {
                    //删除管理员
                    if(channelGroupUserQuery.getJurisdiction() == 1 || channelGroupUserQuery.getJurisdiction() == 2){
                        ChannelGroupJurisdictionQuery channelGroupJurisdictionQuery = new ChannelGroupJurisdictionQuery();
                        channelGroupJurisdictionQuery.setJurisdiction(channelGroupUserQuery.getJurisdiction());
                        channelGroupJurisdictionQuery.setUserId(next.getUserId());
                        List<ChannelGroupJurisdictionListVO> select = channelGroupJurisdictionService.select(channelGroupJurisdictionQuery, tokenUser.getSiteId());
                        if(!CollectionUtils.isEmpty(select)){
                            channelGroupJurisdictionService.deleteByIds(tokenUser,select.get(0).getId());
                        }
                    }else if (channelGroupUserQuery.getJurisdiction() == -1){
                        ChannelGroupUserQuery channelGroupUserQuery1 = new ChannelGroupUserQuery();
                        channelGroupUserQuery1.setGroupId(channelGroupUserQuery.getGroupId());
                        channelGroupUserQuery1.setUserId(next.getUserId());
                        List<ChannelGroupUserListVO> select = select(channelGroupUserQuery1, tokenUser.getSiteId());
                        if(!CollectionUtils.isEmpty(select)){
                            deleteByIds(tokenUser,select.get(0).getId());
                        }
                    }
                    iterator.remove();
                }
            }
        }
        if (!StringUtils.isEmpty(channelGroupUserQuery.getUserName())) {

            channelGroupUserListVOList = channelGroupUserListVOList.stream().filter(p -> p.getUserName().contains(channelGroupUserQuery.getUserName()))
                    .collect(Collectors.toList());
        }
        return channelGroupUserListVOList;
    }

    @Override
    public List<ChannelGroupUserDO> getAllManagerByGroupId(String channelGroupId, TokenUser tokenUser) {
        Example example = new Example(ChannelGroupUserDO.class);
        example.and()
                .andEqualTo("valid", true)
                .andEqualTo("siteId", tokenUser.getSiteId())
                .andEqualTo("channelGroupId", channelGroupId);
        return channelGroupUserDAO.selectByExample(example);
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public ChannelGroupUserVO save(ChannelGroupUserAddDTO channelGroupUserAddDTO, TokenUser tokenUser) {
        // 转DO
        ChannelGroupUserDO channelGroupUserDO = channelGroupUserAddDTO.to(ChannelGroupUserDO.class);
        // 保存
        channelGroupUserDO = save(channelGroupUserDO, tokenUser.getSiteId(), tokenUser.getUserId());
        return channelGroupUserDO.to(ChannelGroupUserVO.class);
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public int update(ChannelGroupUserUpdateDTO channelGroupUserUpdateDTO, TokenUser tokenUser) {
        //转DO
        ChannelGroupUserDO channelGroupUserDO = channelGroupUserUpdateDTO.to(ChannelGroupUserDO.class);
        //根据主键更新，只更新非null值
        return updateByIdSelective(channelGroupUserDO, tokenUser.getSiteId(), tokenUser.getUserId());
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public int deleteByIds(TokenUser tokenUser, String... channelGroupUserIds) {
        return logicalDeleteByIds(tokenUser.getSiteId(), tokenUser.getUserId(), (Object[]) channelGroupUserIds);
    }


    @Override
    public ChannelGroupUserVO selectById(String channelGroupUserId, String siteId) {
        ChannelGroupUserDO channelGroupUserDO = selectDOById(channelGroupUserId, siteId);
        if (channelGroupUserDO == null) {
            return null;
        }
        return channelGroupUserDO.to(ChannelGroupUserVO.class);
    }

    @Override
    public List<ChannelGroupUserListVO> select(ChannelGroupUserQuery channelGroupUserQuery, String siteId) {
        List<ChannelGroupUserDO> channelGroupUserDOList = selectDO(channelGroupUserQuery, siteId);
        if (CollectionUtils.isEmpty(channelGroupUserDOList)) {
            return channelGroupUserDOList == null ? null : new ArrayList<>();
        }
        return channelGroupUserDOList.stream()
                .map(channelGroupUserDO -> channelGroupUserDO.to(ChannelGroupUserListVO.class))
                .collect(Collectors.toList());
    }

    @Override
    public int selectCount(ChannelGroupUserQuery channelGroupUserQuery, String siteId) {
        Example example = buildExample(channelGroupUserQuery, siteId);
        return channelGroupUserDAO.selectCountByExample(example);
    }

    @Override
    public Page<ChannelGroupUserListVO> selectPage(ChannelGroupUserQuery channelGroupUserQuery, String siteId) {
        Example example = buildExample(channelGroupUserQuery, siteId);
        Page<ChannelGroupUserDO> page = channelGroupUserDAO.selectPageByExample(example,
                channelGroupUserQuery.getPageNo(),
                channelGroupUserQuery.getPageSize());

        return page.to(ChannelGroupUserListVO.class);
    }

    @Override
    public ChannelGroupUserDO selectDOById(String channelGroupUserId, String siteId) {
        return listById(channelGroupUserId, siteId);
    }

    @Override
    public List<ChannelGroupUserDO> selectDO(ChannelGroupUserQuery channelGroupUserQuery, String siteId) {
        Example example = buildExample(channelGroupUserQuery, siteId);
        return channelGroupUserDAO.selectByExample(example);
    }


    /**
     * 根据查询参数，构建example
     *
     * @param channelGroupUserQuery 查询参数
     * @param siteId                所属站点id
     * @return example
     */
    private Example buildExample(ChannelGroupUserQuery channelGroupUserQuery, String siteId) {
        Example example = new Example(ChannelGroupUserDO.class);
        example.and()
                .andEqualTo("valid", true)
                .andEqualTo("siteId", siteId);
        if (!StringUtils.isEmpty(channelGroupUserQuery.getUserId())) {
            example.and().andEqualTo("userId", channelGroupUserQuery.getUserId());
        }
        if (!StringUtils.isEmpty(channelGroupUserQuery.getGroupId())) {
            example.and().andEqualTo("channelGroupId", channelGroupUserQuery.getGroupId());
        }
        // 排序
        ExampleKit.setExampleOrder(example, channelGroupUserQuery.getOrders());
        return example;
    }
}




